﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.MeetingReservations;
using B.S.Meeting.ReadAPI.Dtos;
using MediatR;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.MeetingReservations
{
    public class GetReservationCommandHandler : IRequestHandler<GetReservationCommand, APIResult<APIPaging<List<ReservationDto>>>>
    {
        IBaseRepository<MeetingRoom> rRep;
        IBaseRepository<MeetingReservation> mtrRep;
        IMapper mapper;
        ILogger<GetReservationCommandHandler> logger;

        public GetReservationCommandHandler(IBaseRepository<MeetingReservation> mtrRep, IMapper mapper, ILogger<GetReservationCommandHandler> logger, IBaseRepository<MeetingRoom> rRep)
        {
            this.mtrRep = mtrRep;
            this.mapper = mapper;
            this.logger = logger;
            this.rRep = rRep;
        }

        public async Task<APIResult<APIPaging<List<ReservationDto>>>> Handle(GetReservationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var roomlist =  rRep.GetAll().Where(x => !x.IsDel);
                var reservationlist=mtrRep.GetAll().Where(x=>!x.IsDel);
                if(!string.IsNullOrEmpty(request.TemplateName))
                {
                    reservationlist = reservationlist.Where(x => x.TemplateName.Contains(request.TemplateName));
                }
                var list = from res in reservationlist
                           join room in roomlist
                           on res.MeetingRoomId equals room.MeetingRoomId
                           select res;
                var totalCount= reservationlist.Count();
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list = list.OrderBy(x => x.MeetingReservationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                var reserDto=mapper.Map<List<ReservationDto>>(list);
                List<MeetingRoom> rooms= rRep.GetAll().ToList();
                foreach(var item in reserDto)
                {
                    item.Location= rooms.Find(x=>x.MeetingRoomId==item.MeetingRoomId).Location;
                }
                return new APIResult<APIPaging<List<ReservationDto>>>
                {
                    Code=StatusEnumCode.Ok,
                    Message="获取会议预约列表成功",
                    Data=new APIPaging<List<ReservationDto>>
                    {
                        TotalCount=totalCount,
                        TotalPage=totalPage,
                        Data=reserDto.ToList()
                    }
                };
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
